package de.uni_saarland.coli.doclists.document.iterator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import de.uni_saarland.coli.doclists.document.ITextDocument;
import de.uni_saarland.coli.doclists.document.TextDocument;

public class DocumentIteratorCustomCorpus implements IDocumentIterator {

	private BufferedReader reader;
	private int id;
	
	@Override
	public boolean hasNext() {
		try {
			this.reader.mark(100);
			if(this.reader.ready() && this.reader.readLine().startsWith("#")){
				this.reader.reset();
				return true;
			}
		} catch (IOException e) {
			return false;
		}
		return false;
	}

	@Override
	public ITextDocument next() {
		this.id++;
		StringBuffer text = new StringBuffer();
		String name = "";
		try {
			while(this.reader.ready()){
				try {
					String line = this.reader.readLine().trim();
					if(line.startsWith("#")){
						name = line.split(": ")[1];
						continue;
					}
					if(line.isEmpty())
						break;
					text.append(line + "\n");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TextDocument next = new TextDocument(name, text, this.id);
		return next;
	}

	public DocumentIteratorCustomCorpus(String inFile){
		try {
			this.id = -1;
			this.reader = new BufferedReader(new FileReader(new File(inFile)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
